package pl.bristleback.server.bristle.exceptions.handlers;

import org.apache.log4j.Logger;
import org.jwebsocket.api.WebSocketConnector;
import org.jwebsocket.token.Token;

import java.util.HashMap;
import java.util.Map;

/**
 * This class is a simple container for exception handlers.
 * Every occurring exception which can be handled and collected here is caused by user.
 * Actual list of exceptions possible to handle can be found in
 * {@link ActionExceptionType} enum.
 * <p/>
 * Created on: 2010-10-23 23:56:13 <br/>
 *
 * @author Wojciech Niemiec
 */
public class ExceptionHandlersContainer {
  private static Logger log = Logger.getLogger(ExceptionHandlersContainer.class.getName());

  private Map<ActionExceptionType, ExceptionHandler> exceptionHandlers;

  /**
   * Creates a empty exception handlers container.
   */
  public ExceptionHandlersContainer() {
    exceptionHandlers = new HashMap<ActionExceptionType, ExceptionHandler>();
  }

  /**
   * Invokes (if exists) handler for given exception type. Information about connector and token is passed to handler.
   *
   * @param actionExceptionType exception type to handle.
   * @param connector     websocket connector.
   * @param token         content of message sent by connector.
   */
  public void invokeHandler(ActionExceptionType actionExceptionType, WebSocketConnector connector, Token token) {
    ExceptionHandler exceptionHandler = exceptionHandlers.get(actionExceptionType);
    if (exceptionHandler != null) {
      exceptionHandler.handleException(connector, token);
    }
  }

  /**
   * Adds a handler to container. Note that in current version of Bristle plugin,
   * there is no way to have multiple handlers for the same exception type.
   *
   * @param actionExceptionType type of exception to handle.
   * @param handler       exception handler implementation.
   */
  public void addHandler(ActionExceptionType actionExceptionType, ExceptionHandler handler) {
    exceptionHandlers.put(actionExceptionType, handler);
  }
}
